<?php

namespace App\Admin\Renderable;

use App\Models\Administrator;
use Carbon\Carbon;
use Dcat\Admin\Grid;
use Dcat\Admin\Grid\LazyRenderable;
use Illuminate\Support\Facades\Cache;


class DispatchUserTable extends LazyRenderable
{
    public function grid(): Grid
    {
        $groupId = data_get($this->payload, 'group_id');
        // 获取外部传递的参数
        $q = Administrator::query()
            ->whereHas('roles', function ($query) {
                $query->where('slug', 'base_form_dispatch');
            });

        if ($groupId) {
            $q->whereHas('group' , function ($query )use ($groupId) {
                $query->where('group_id', $groupId);
            });
        }

        return Grid::make($q, function (Grid $grid)  {
            $grid->column('id');
            $grid->column('username');
            $grid->column('name');

            $grid->column('_any_', '今天分配数量')
                ->display(function () {
                    $date = Carbon::today()->toDateString();
                    $var = Cache::get("$date.{$this->id}") ?? 0;
//                    if ($var)
//                        dd($var , $this->id);
                    return $var;
                });
            $grid->column('dispatch_limit', '日分配上限');
            $grid->column('online', '在线状态')->bool();

            $grid->quickSearch(['id', 'username', 'name']);

            $grid->paginate(10);
            $grid->disableActions();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('username')->width(4);
                $filter->like('name')->width(4);
            });
        });
    }
}
